# -*- coding: utf-8 -*-
import os
import uuid
import requests
from shutil import copyfileobj
from config.Common import base_work_dir
from utils.FtpUtil import FtpUtil
from config.LoadConfig import get_config
from utils.PathUtil import build_save_file_dir

__data_dir=build_save_file_dir("datas")
__save_dir=f"{__data_dir}/download"
if not os.path.exists(__save_dir):
    os.makedirs(__save_dir)


def download_file(file_url, file_system_type: str = "url", ext_params: dict = {}):
    """
    下载文件
    :param file_url: 文件的URL或本地路径
    :ext_params = 扩充参数
    :return: 下载文件的路径
    """
    local_filename = __get_local_filename(file_url)
    try:
        if file_system_type == "ftp":
            __download_file_from_ftp(ext_params, file_url, local_filename)
        else:
            if __is_http_url(file_url):
                __download_from_http(file_url, local_filename)
            else:
                __copy_local_file(file_url, local_filename)
        return local_filename
    except Exception as e:
        raise e

def __download_file_from_ftp(ext_params:dict, file_url, local_filename):
    """
    从FTP服务器下载文件
    :param ext_params: 扩展参数，包含ftpClient
    """
    ext_params = ext_params or {}
    ftp_client = ext_params.get("ftpClient") if "ftpClient" in ext_params else None
    if ftp_client is None:
        ftp_client = FtpUtil(ext_params)
        ext_params.update({"ftpClient": ftp_client})
    ftp_client.download_file(file_url, local_filename)

def __get_local_filename(file_url):
    """
    从URL或路径中提取文件名，并使用UUID作为新的文件名，保留原始文件后缀
    """
    if __is_http_url(file_url):
        parsed_url = requests.utils.urlparse(file_url)
        path = parsed_url.path
        path = path.split('?')[0].split('#')[0]
        file_name = os.path.basename(path)
        _, file_extension = os.path.splitext(file_name)
        new_file_name = f"{uuid.uuid4()}{file_extension}"
        return f"{__save_dir}/{new_file_name}"
    else:
        file_name = os.path.basename(file_url)
        _, file_extension = os.path.splitext(file_name)
        new_file_name = f"{uuid.uuid4()}{file_extension}"
        return f"{__save_dir}/{new_file_name}"


def __is_http_url(url):
    """
    检查URL是否是HTTP或HTTPS协议
    """
    parsed_url = requests.utils.urlparse(url)
    return parsed_url.scheme in ('http', 'https')

def __download_from_http(file_url, local_filename):
    """
    从HTTP URL下载文件
    """
    with requests.get(file_url, stream=True) as r:
        r.raise_for_status()
        with open(local_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)
            f.close()

def __copy_local_file(file_url, local_filename):
    """
    从本地路径复制文件
    """
    with open(file_url, 'rb') as fsrc:
        with open(local_filename, 'wb') as fdst:
            copyfileobj(fsrc, fdst)



    
def remove_img(image_path):
    '''
    移除一张图片
    '''
    if os.path.exists(image_path):
        os.remove(image_path)


if __name__ == '__main__':
    # 使用示例
    file_path = download_file('http://10.118.21.239:91/dev/20221205/ANNEX/137-589874455-111111-111111-1670226912-00011/th_ebbd4de9229f83e067e685a6142673a3')
    print(f"文件已下载到: {file_path}")

    # file_path = downloader.download_file('/path/to/your/local/file.txt')
    # print(f"文件已下载到: {file_path}")
    pass